package com.lipaluma.excel.io;

import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.lipaluma.io.SourceReader;

/**
 * Reader For Excel File
 * @author Mario
 */
public class ExcelReader implements SourceReader {

	private Workbook workbook;
	private int currentRow = 0;
	private int nextRow = 0;
	private InputStream inputStream;
	private int sheetIndex = 0;
	
	/**
	 * Construct an Excel Reader by the Workbook representing the entry file
	 * @param workbook
	 */
	public ExcelReader(Workbook workbook) {
		this.workbook = workbook;
	}
	/**
	 * Construct an Excel Reader by the Workbook representing the entry file at the sheet index
	 * @param workbook
	 * @param sheetIndex the index of the sheet
	 */
	public ExcelReader(Workbook workbook, int sheetIndex) {
		this.workbook = workbook;
		this.sheetIndex = sheetIndex;
	}
	/**
	 * Construct an Excel Reader by the Workbook representing the entry file with the sheet name
	 * @param workbook
	 * @param sheetName the name of the sheet
	 */
	public ExcelReader(Workbook workbook, String sheetName) {
		this.workbook = workbook;
		this.sheetIndex = workbook.getSheetIndex(sheetName);
	}

	public int getCurrentLineNumber() {
		return currentRow;
	}
	
	public boolean hasNext() {
		Sheet sheet = workbook.getSheetAt(sheetIndex);
		return nextRow <= sheet.getLastRowNum();
	}

	public com.lipaluma.io.Row next() {
		currentRow = nextRow;
		Sheet sheet = workbook.getSheetAt(sheetIndex);
		Row row = sheet.getRow(nextRow++);
		
		return new ExcelRow(workbook, row);
	}
	
	public void close() {
		IOUtils.closeQuietly(inputStream);
	}
}
